package com.blackoreo.monitor.servlet;

import com.blackoreo.monitor.cache.BlackOreoCache;
import freemarker.template.Configuration;
import freemarker.template.Template;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * PackageName: com.blackoreo.monitor.servlet
 * Author: txw
 * Date: 2021/4/8
 * Description: Custom servlet handler for monitor service.
 */
public class MonitorServlet extends HttpServlet {
    static Configuration configuration = new Configuration(Configuration.VERSION_2_3_0);
    static Template monitorTemplate;
    static {
        configuration.setClassForTemplateLoading(MonitorServlet.class,"/");
        //获取模板
        try {
            monitorTemplate = configuration.getTemplate("black_oreo_monitor.ftl");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter printWriter = resp.getWriter();
        printWriter.write(dataBind(BlackOreoCache.generateData()));
    }

    private String dataBind(Object data) {
        try(StringWriter stringWriter = new StringWriter()) {
            monitorTemplate.process(data, stringWriter);
            return stringWriter.toString();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
